from flask import current_app, Blueprint, request
from flask_json import as_json
from flask_jwt_extended import jwt_required

from app import db
from app.admin.is_staff_user import is_staff_user
from app.models import CommonResult, AuthRole, AuthRolePermission, AuthUserRole
from app.common.enums import AuthRoleStatus, RoleCodeEnum
from app.form.auth_role_form import AuthRoleForm
from app.auth.auth_decorator import has_role

log = current_app.logger
admin_role = Blueprint('admin_role', __name__, url_prefix='/admin/role')


# 注册蓝图
def register_controller(app):
    app.register_blueprint(admin_role)


# 列表查询
@admin_role.post('/list')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def admin_role_list():
    data = request.get_json()
    query = AuthRole.query
    # 传入状态参数，查询对应的角色
    if data and data.get("role_status") is not None:
        role_status = AuthRoleStatus._value2member_map_.get(data.get("role_status"))
        query = query.filter(AuthRole.role_status == role_status)
    data_list = query.all()
    return CommonResult(data=data_list)


# 获取详情
@admin_role.get('/get/<int:role_id>')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def info(role_id):
    record_info = AuthRole.query.get(role_id)
    if record_info is None:
        return CommonResult(code=500, msg='记录不存在')
    return CommonResult(data=record_info, msg='获取成功')


# 添加记录
@admin_role.post('/add')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def add():
    AuthRoleForm().api_validate()
    data = request.get_json()
    # 填充数据
    record = AuthRole()
    record.__dict__.update(data)
    # 保存数据库
    db.session.add(record)
    db.session.commit()
    return CommonResult(data=data, msg='保存成功')


@admin_role.post('/update')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def update():
    AuthRoleForm().api_validate()
    data = request.get_json()
    if data and data.get('id') is not None:
        record = AuthRole.query.get(data.get('id'))
        if record is None:
            return CommonResult(code=500, msg='修改记录不存在')
        db.session.query(AuthRole).filter(AuthRole.id == data.get('id')).update(data)
        db.session.commit()
        return CommonResult(data=data, msg='修改成功')
    return CommonResult(code=500, msg='请传入修改记录的ID')


# 删除记录
@admin_role.get('/delete/<int:role_id>')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def delete(role_id):
    # 查询是否存在
    record = AuthRole.query.get(role_id)
    if record is None:
        return CommonResult(code=500, msg='删除的记录不存在')
    # 删除主记录和关联记录
    db.session.query(AuthRolePermission).filter(AuthRolePermission.role_id == role_id).delete()
    db.session.query(AuthUserRole).filter(AuthUserRole.role_id == role_id).delete()
    db.session.delete(record)
    db.session.commit()
    return CommonResult(msg='删除成功')
